//
//  SetViewController.m
//  SouthChina
//
//  Created by Mr.Y on 14/12/24.
//  Copyright (c) 2014年 科创. All rights reserved.
//

#import "SetViewController.h"
#import "PersonalCenterTableViewCell.h"
#import "FriendSetViewController.h"
#import "MessageRemindViewController.h"
#import "AboutViewController.h"
#import "MessageSessionDao.h"
#import "MessageListViewController.h"
#import "SDImageCache.h"
#import "ContactDao.h"
#import "MessageDao.h"

@interface SetViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,UIActionSheetDelegate>
{
    NSArray *titlespic; //标题图片
}
@property (strong, nonatomic) NSArray * titles;

@end

@implementation SetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addTitleBarWithBackBtn:@"设置" needReturn:YES];
    titlespic = @[@[@"set_friend.png",@"set_clear.png"],@[@"set_alarm.png"/*,@"set_check.png"*/],@[@"set_txl.png"]];
    _titles = @[@[@"好友设置",@"清除消息记录"],@[@"消息提醒"/*,@"检查更新"*/],@[@"同步通讯录"]];
    _setTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    _setTableview.delegate = self;
    _setTableview.dataSource = self;
    _setTableview.bounces = NO;
    [self.view addSubview:_setTableview];
    self.view.backgroundColor = [UIColor colorWithRed:236/255.0f green:235/255.0f blue:243/255.0f alpha:1];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _titles.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray * arr = [self.titles objectAtIndex:section];
    return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"PersonalCenterTableViewCell";
    PersonalCenterTableViewCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
    }
    cell.labelconstraint.constant= 36;
    cell.titleLabel.font = [UIFont systemFontOfSize:15];
    cell.titleLabel.text = _titles[indexPath.section][indexPath.row];
    UIImageView *cellimage =  [[UIImageView alloc] initWithFrame:CGRectMake(15, 12,24, 24)];
    cellimage.image = [UIImage imageNamed:titlespic[indexPath.section][indexPath.row]];
    [cell addSubview:cellimage];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSLog(@"section:%ld  indexpath:%ld",(long)indexPath.section,(long)indexPath.row);
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后颜色消失
    switch (indexPath.section) {
        case 0:
            if (indexPath.row == 0) {
                FriendSetViewController * friendset = [[FriendSetViewController alloc]init];
                [kAppDelegate.iCSDrawerController.navigationController pushViewController:friendset animated:NO];
            }
            else if(indexPath.row == 1){
                UIActionSheet * sheet = [[UIActionSheet alloc] initWithTitle:@"将清空所有系统和个人的消息记录" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"清除一周前的消息" otherButtonTitles:@"清除一月前的消息",@"清空消息记录",@"清除本地图片缓存", nil];
                sheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
                [sheet showInView:self.view];
            }
            break;
        case 1:
            if (indexPath.row == 0) {
                MessageRemindViewController * messageremind = [[MessageRemindViewController alloc] init];
                [kAppDelegate.iCSDrawerController.navigationController pushViewController:messageremind animated:NO];
            }
            /*else if (indexPath.row == 1) {
                [self checkNewVersion];
            }*/
            break;
        case 2:
           if (indexPath.row == 0) {// 同步通讯录
               [self refreshAdBookForced];
            }
            break;
        default:
            break;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 26;
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSDate *  senddate=[NSDate date];
    NSDate *sevenDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:([senddate timeIntervalSinceReferenceDate] - 7*24*3600)];
    NSDate *mouthDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:([senddate timeIntervalSinceReferenceDate] - 7*24*3600)];

    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd"];
    NSString *  sevenDateString=[dateformatter stringFromDate:sevenDate];
    NSString *  mouthDateString=[dateformatter stringFromDate:mouthDate];

    switch (buttonIndex) {
        case 0:
            [MessageSessionDao deleteMessageByTime:sevenDateString];
            kAppDelegate.needRefrsh = YES;
            [self showAlerHUD:@"清除一周前消息成功！"];
            
            break;
        case 1:
            [MessageSessionDao deleteMessageByTime:mouthDateString];
            kAppDelegate.needRefrsh = YES;
            [self showAlerHUD:@"清除一月前消息成功！"];
            break;
        case 2:
            [MessageSessionDao deleteMessageSessionAll];
            [MessageDao deleteMessageAll];
            kAppDelegate.needRefrsh = YES;
            [self showAlerHUD:@"清除所有消息成功！"];
            break;
        case 3:
            //TODO 清除图片缓存
            [[SDImageCache sharedImageCache] clearDisk];
            [[SDImageCache sharedImageCache] clearMemory ];

            [self showAlerHUD:@"清除图片缓存成功！"];
            break;

        default:
            break;
    }

}

/*
-(void)checkNewVersion
{
    //版本检测
    NSDictionary *userInfo = @{@"appVersion":APPVERSION};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [DE serverCall:@"versionCheck" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if(success){
            if (!data  || ![data objectForKey:@"VERSION_ESN"]) {
                  alert.message = @"当前已是最新版本！";
                [alert addButtonWithTitle:@"确定"];
            }else{
                alert.message = @"发现新版本！";
                [alert addButtonWithTitle:@"取消"];
                [alert addButtonWithTitle:@"前往App Store下载"];
            }
        }else{
            alert.message =@"检测版本失败！";
            [alert addButtonWithTitle:@"确定"];
            
        }
        [alert show];

    }];
}
*/

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==0) {
     
    }/*else{
        //TODO 去苹果商店
       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms://itunes.apple.com/cn/"]];

    }*/
}


//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(void)refreshAdBookForced
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [DE serverCall:@"refreshAdBookForced" params:[[NSDictionary alloc] init] callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param)
     {
         
         dispatch_async(dispatch_get_main_queue(), ^{
             [MBProgressHUD hideHUDForView:self.view animated:YES];
             
             if (success) {
                 // 优先更新通讯录
                 NSDictionary* txl = [data objectForKey:@"txl"];
                 if (txl!=nil) {
                     NSString *txlVersion = [txl objectForKey:@"version"];
                     [DE setGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]] value:txlVersion];
                     NSArray * txlls = [txl objectForKey:@"updates"];
                     [ContactDao updataDBwithSQLiteStatement:txlls clearFisrt:YES];
                     
                     [[NSNotificationCenter defaultCenter] postNotificationName:CONTACT_CHANGE_BROADCAST object:nil];
                     
                 }
             }
             
             UIAlertView * aler =  [[UIAlertView alloc] initWithTitle:@"提示" message:success?@"更新通讯录成功！":@"更新通讯录失败！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
             [aler show];
         });
         
     }];
}


@end
